import { Injectable, Logger, OnModuleInit } from '@nestjs/common'
import { Cron } from '@nestjs/schedule'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { MenuEntity } from '../entities/menu.entity'
import { OrderEntity } from '@/src/order/entities/order.entity'

@Injectable()
export class MenuScheduleService implements OnModuleInit {
  private readonly logger = new Logger(MenuScheduleService.name)
  private readonly isProd: boolean

  constructor(
    @InjectRepository(MenuEntity)
    private readonly menuRepository: Repository<MenuEntity>,
    @InjectRepository(OrderEntity)
    private readonly orderRepository: Repository<OrderEntity>
  ) {
    // 容错处理：默认视为开发环境
    const nodeEnv = process.env.NODE_ENV?.toLowerCase() || 'development'
    this.isProd = nodeEnv === 'production'
  }

  // 本地启动项目时自动执行一次新品过期检查（开发环境）
  async onModuleInit() {
    if (!this.isProd) {
      console.log('【开发环境】启动时执行新品过期检查任务...')
      await Promise.all([
        this.checkNewMenu(),
      ])
    }
  }

  // 线上定时任务：每天凌晨3点执行（仅生产环境生效）
  @Cron('0 0 3 * * *', { timeZone: 'Asia/Shanghai' })
  async handleNewItemExpiration() {
    if (this.isProd) {
      console.log('【生产环境】定时执行新品过期检查任务...')
      await Promise.all([
        this.checkNewMenu(),
      ])
    }
  }

  // 检查并更新过期新品
  private async checkNewMenu() {
    try {
      const sevenDaysAgo = Math.floor(Date.now() / 1000) - 7 * 24 * 60 * 60
      const result = await this.menuRepository
        .createQueryBuilder()
        .update(MenuEntity)
        .set({ is_new: 0 })
        .where('is_new = 1 AND create_time <= :sevenDaysAgo', { sevenDaysAgo })
        .execute()

      console.log(`新品过期检查完成，已将 ${result.affected || 0} 个菜品标记为非新品`)
    } catch (error) {
      console.error('新品过期检查任务执行失败', error.stack)
    }
  }
}
